// 日志聚合规则配置系统
const LogAggregator = {
    // 数据存储
    rules: [],
    logData: [],
    events: [],
    currentEditRuleId: null,
    
    // DOM元素缓存
    dom: {},
    
    // 初始化函数
    init: function() {
        this.cacheDomElements();
        this.initEventListeners();
        this.updateCorrelationPreview();
        this.updateRuleDescription();
        this.loadRules(); // 从localStorage加载规则
        
        // 添加延迟以确保动画效果正常显示
        setTimeout(() => {
            this.renderRulesList();
        }, 100);
    },
    
    // 缓存DOM元素
    cacheDomElements: function() {
        // 规则配置表单
        this.dom.ruleName = document.getElementById('rule-name');
        this.dom.source1Type = document.getElementById('source1-type');
        this.dom.source1Filter = document.getElementById('source1-filter');
        this.dom.source2Type = document.getElementById('source2-type');
        this.dom.source2Filter = document.getElementById('source2-filter');
        this.dom.aggregationWindow = document.getElementById('aggregation-window');
        this.dom.windowUnit = document.getElementById('window-unit');
        this.dom.thresholdType = document.getElementById('threshold-type');
        this.dom.thresholdCount = document.getElementById('threshold-count');
        this.dom.ruleDescription = document.getElementById('rule-description');
        this.dom.correlationPreview = document.getElementById('correlation-preview');
        this.dom.source1FieldDisplay = document.getElementById('source1-field-display');
        this.dom.source2FieldDisplay = document.getElementById('source2-field-display');
        
        // 按钮
        this.dom.saveRuleBtn = document.getElementById('save-rule');
        this.dom.applyRuleBtn = document.getElementById('apply-rule');
        this.dom.clearRuleBtn = document.getElementById('clear-rule');
        this.dom.importRulesBtn = document.getElementById('import-rules-btn');
        this.dom.exportRulesBtn = document.getElementById('export-rules-btn');
        this.dom.generateLogsBtn = document.getElementById('generate-logs');
        this.dom.viewEventsBtn = document.getElementById('view-events');
        
        // 容器
        this.dom.rulesContainer = document.getElementById('rules-container');
        this.dom.simulationResults = document.getElementById('simulation-results');
        this.dom.fileInput = document.getElementById('file-input');
        
        // 新增展示框相关元素
        this.dom.resultsContent = document.getElementById('results-content');
        this.dom.clearResultsBtn = document.getElementById('clear-results');
    },
    
    // 初始化事件监听器
    initEventListeners: function() {
        // 日志源配置变化监听
        this.dom.source1Type.addEventListener('change', () => this.updateFilterOptions(this.dom.source1Type, this.dom.source1Filter, 'source1'));
        this.dom.source2Type.addEventListener('change', () => this.updateFilterOptions(this.dom.source2Type, this.dom.source2Filter, 'source2'));
        this.dom.source1Filter.addEventListener('change', this.updateCorrelationPreview.bind(this));
        this.dom.source2Filter.addEventListener('change', this.updateCorrelationPreview.bind(this));
        
        // 聚合配置变化监听
        this.dom.aggregationWindow.addEventListener('input', this.updateRuleDescription.bind(this));
        this.dom.windowUnit.addEventListener('change', this.updateRuleDescription.bind(this));
        this.dom.thresholdType.addEventListener('change', this.updateRuleDescription.bind(this));
        this.dom.thresholdCount.addEventListener('input', this.updateRuleDescription.bind(this));
        this.dom.ruleName.addEventListener('input', this.updateRuleDescription.bind(this));
        
        // 按钮事件监听
        this.dom.saveRuleBtn.addEventListener('click', this.saveRule.bind(this));
        this.dom.applyRuleBtn.addEventListener('click', this.applyCurrentRule.bind(this));
        this.dom.clearRuleBtn.addEventListener('click', this.clearRuleForm.bind(this));
        this.dom.importRulesBtn.addEventListener('click', () => this.dom.fileInput.click());
        this.dom.exportRulesBtn.addEventListener('click', this.exportRules.bind(this));
        this.dom.generateLogsBtn.addEventListener('click', this.generateSimulatedLogs.bind(this));
        this.dom.viewEventsBtn.addEventListener('click', this.viewTriggeredEvents.bind(this));
        
        // 清空结果按钮事件
        if (this.dom.clearResultsBtn) {
            this.dom.clearResultsBtn.addEventListener('click', () => this.clearResults());
        }
        
        // 文件导入监听
        this.dom.fileInput.addEventListener('change', (e) => {
            if (e.target.files && e.target.files[0]) {
                this.importRules(e.target.files[0]);
                e.target.value = ''; // 重置文件输入
            }
        });
    },
    
    // 更新过滤选项
    updateFilterOptions: function(typeSelect, filterSelect, sourceType) {
        const sourceTypeValue = typeSelect.value;
        
        // 清空现有选项
        filterSelect.innerHTML = '';
        
        // 根据日志源类型添加对应的过滤字段
        let options = [];
        
        if (sourceTypeValue === 'attack') {
            options = [
                { value: 'source_ip', text: '源地址' },
                { value: 'dest_ip', text: '目标地址' },
                { value: 'attack_type', text: '攻击类型' },
                { value: 'severity', text: '严重程度' }
            ];
        } else if (sourceTypeValue === 'auth') {
            options = [
                { value: 'source_ip', text: '源地址' },
                { value: 'username', text: '用户名' },
                { value: 'auth_type', text: '认证类型' },
                { value: 'status', text: '状态' }
            ];
        } else if (sourceTypeValue === 'access') {
            options = [
                { value: 'source_ip', text: '源地址' },
                { value: 'user_agent', text: '用户代理' },
                { value: 'url', text: '访问URL' },
                { value: 'method', text: '请求方法' }
            ];
        } else if (sourceTypeValue === 'system') {
            options = [
                { value: 'hostname', text: '主机名' },
                { value: 'service', text: '服务名称' },
                { value: 'level', text: '日志级别' },
                { value: 'message', text: '日志内容' }
            ];
        }
        
        // 添加选项到select
        options.forEach(option => {
            const opt = document.createElement('option');
            opt.value = option.value;
            opt.textContent = option.text;
            filterSelect.appendChild(opt);
        });
        
        // 更新关联预览
        this.updateCorrelationPreview();
    },
    
    // 更新关联预览
    updateCorrelationPreview: function() {
        const source1Field = this.dom.source1Filter.options[this.dom.source1Filter.selectedIndex].text;
        const source2Field = this.dom.source2Filter.options[this.dom.source2Filter.selectedIndex].text;
        
        this.dom.source1FieldDisplay.textContent = source1Field;
        this.dom.source2FieldDisplay.textContent = source2Field;
        
        // 更新规则描述
        this.updateRuleDescription();
    },
    
    // 获取字段显示名称
    getFieldDisplayName: function(field) {
        const fieldMap = {
            'source_ip': '源地址',
            'dest_ip': '目标地址',
            'username': '用户名',
            'event_type': '事件类型',
            'attack_type': '攻击类型',
            'severity': '严重程度',
            'auth_type': '认证类型',
            'status': '状态',
            'user_agent': '用户代理',
            'url': '访问URL',
            'method': '请求方法',
            'hostname': '主机名',
            'service': '服务名称',
            'level': '日志级别',
            'message': '日志内容'
        };
        
        return fieldMap[field] || field || '未知字段';
    },
    
    // 获取日志类型显示名称
    getLogTypeDisplayName: function(type) {
        const typeMap = {
            'attack': '攻击日志',
            'auth': '认证日志',
            'access': '访问日志'
        };
        
        return typeMap[type] || type || '未知类型';
    },
    
    // 更新规则描述
    updateRuleDescription: function() {
        const ruleName = this.dom.ruleName.value || '未命名规则';
        const source1Type = this.dom.source1Type.options[this.dom.source1Type.selectedIndex].text;
        const source2Type = this.dom.source2Type.options[this.dom.source2Type.selectedIndex].text;
        const source1Field = this.dom.source1Filter.options[this.dom.source1Filter.selectedIndex].text;
        const source2Field = this.dom.source2Filter.options[this.dom.source2Filter.selectedIndex].text;
        const windowValue = this.dom.aggregationWindow.value;
        const windowUnit = this.dom.windowUnit.options[this.dom.windowUnit.selectedIndex].text;
        const thresholdType = this.dom.thresholdType.options[this.dom.thresholdType.selectedIndex].text;
        const thresholdCount = this.dom.thresholdCount.value;
        
        const description = `规则「${ruleName}」：将${source1Type}和${source2Type}通过${source1Field}和${source2Field}进行关联，在${windowValue}${windowUnit}的聚合窗口内，当关联后的事件${thresholdType}${thresholdCount}次时触发告警。`;
        
        this.dom.ruleDescription.textContent = description;
    },
    
    // 保存规则
    saveRule: function() {
        // 验证表单
        if (!this.dom.ruleName.value.trim()) {
            this.showNotification('请为规则输入一个名称，方便后续识别和管理', 'warning');
            return;
        }
        
        // 创建规则对象
        const rule = {
            id: this.currentEditRuleId || Date.now().toString(),
            name: this.dom.ruleName.value.trim(),
            source1: {
                type: this.dom.source1Type.value,
                filter: this.dom.source1Filter.value,
                displayType: this.dom.source1Type.options[this.dom.source1Type.selectedIndex].text,
                displayFilter: this.dom.source1Filter.options[this.dom.source1Filter.selectedIndex].text
            },
            source2: {
                type: this.dom.source2Type.value,
                filter: this.dom.source2Filter.value,
                displayType: this.dom.source2Type.options[this.dom.source2Type.selectedIndex].text,
                displayFilter: this.dom.source2Filter.options[this.dom.source2Filter.selectedIndex].text
            },
            aggregation: {
                window: parseInt(this.dom.aggregationWindow.value),
                unit: this.dom.windowUnit.value,
                threshold: {
                    type: this.dom.thresholdType.value,
                    count: parseInt(this.dom.thresholdCount.value)
                }
            },
            description: this.dom.ruleDescription.textContent,
            createdAt: this.currentEditRuleId ? this.rules.find(r => r.id === this.currentEditRuleId)?.createdAt : new Date().toISOString(),
            updatedAt: new Date().toISOString()
        };
        
        // 检查是更新还是新增
        if (this.currentEditRuleId) {
            const index = this.rules.findIndex(r => r.id === this.currentEditRuleId);
            if (index !== -1) {
                this.rules[index] = rule;
                this.showNotification('规则更新成功', 'success');
            }
        } else {
            this.rules.unshift(rule);
            this.showNotification('规则保存成功', 'success');
        }
        
        // 保存到localStorage
        this.saveRulesToLocalStorage();
        
        // 渲染规则列表
        this.renderRulesList();
        
        // 重置表单
        this.clearRuleForm();
    },
    
    // 应用当前规则
    applyCurrentRule: function() {
        // 生成模拟数据
        this.generateSimulatedLogs();
        
        const rule = {
            source1: {
                type: this.dom.source1Type.value,
                filter: this.dom.source1Filter.value
            },
            source2: {
                type: this.dom.source2Type.value,
                filter: this.dom.source2Filter.value
            },
            aggregation: {
                window: parseInt(this.dom.aggregationWindow.value),
                unit: this.dom.windowUnit.value,
                threshold: {
                    type: this.dom.thresholdType.value,
                    count: parseInt(this.dom.thresholdCount.value)
                }
            }
        };
        
        // 应用规则
        this.events = this.applyRule(rule, this.logData);
        
        // 如果应用规则后没有触发事件，则添加一些测试事件以确保有内容展示
        if (this.events.length === 0) {
            // 生成一些额外的测试事件
            const specialIp = '192.168.1.100';
            const sampleRule = { ...rule, name: '生成的测试规则' };
            
            // 查找特定IP的日志
            const source1Logs = this.logData.filter(log => log.type === rule.source1.type);
            const source2Logs = this.logData.filter(log => log.type === rule.source2.type);
            
            // 创建一个通用的测试事件
            if (source1Logs.length > 0 && source2Logs.length > 0) {
                this.events.push({
                    id: Date.now() + '_test_event_1',
                    correlationKey: specialIp,
                    count: source1Logs.length + source2Logs.length,
                    timestamp: new Date().toISOString(),
                    rule: sampleRule,
                    events: [
                        { log1: source1Logs[0], log2: source2Logs[0], timestamp: Math.max(source1Logs[0].timestamp, source2Logs[0].timestamp) },
                        { log1: source1Logs[1] || source1Logs[0], log2: source2Logs[1] || source2Logs[0], timestamp: Date.now() }
                    ]
                });
            }
        }
        
        // 显示结果
        this.displaySimulationResults(rule, this.events);
        this.showNotification(`规则应用成功，触发了 ${this.events.length} 个事件`, 'success');
    },
    
    // 清除表单
    clearRuleForm: function() {
        this.dom.ruleName.value = '';
        this.dom.aggregationWindow.value = '5';
        this.dom.thresholdCount.value = '50';
        this.currentEditRuleId = null;
        this.updateRuleDescription();
    },
    
    // 渲染规则列表
    renderRulesList: function() {
        this.dom.rulesContainer.innerHTML = '';
        
        if (this.rules.length === 0) {
            const emptyState = document.createElement('div');
            emptyState.className = 'text-center text-text-secondary py-8';
            emptyState.innerHTML = `
                <i class="fa fa-file-text-o text-4xl mb-2 text-gray-300"></i>
                <p>暂无保存的规则</p>
            `;
            this.dom.rulesContainer.appendChild(emptyState);
            return;
        }
        
        // 渲染每个规则
        this.rules.forEach(rule => {
            const ruleItem = document.createElement('div');
            ruleItem.className = 'rule-item slide-in-left';
            ruleItem.dataset.id = rule.id;
            
            // 规则信息
            const ruleInfo = document.createElement('div');
            ruleInfo.className = 'rule-info';
            
            const ruleName = document.createElement('h4');
            ruleName.className = 'font-medium text-text-primary';
            ruleName.textContent = rule.name;
            
            const ruleMeta = document.createElement('p');
            ruleMeta.className = 'text-xs text-text-secondary';
            ruleMeta.textContent = `${rule.source1.displayType} + ${rule.source2.displayType} · ${rule.aggregation.window}${this.getUnitDisplay(rule.aggregation.unit)}窗口`;
            
            ruleInfo.appendChild(ruleName);
            ruleInfo.appendChild(ruleMeta);
            
            // 规则操作
            const ruleActions = document.createElement('div');
            ruleActions.className = 'rule-actions';
            
            // 应用按钮
            const applyBtn = document.createElement('button');
            applyBtn.className = 'p-1.5 text-primary-main hover:bg-primary-light rounded-small transition-colors-300';
            applyBtn.title = '应用规则';
            applyBtn.innerHTML = '<i class="fa fa-play"></i>';
            applyBtn.addEventListener('click', () => this.applySavedRule(rule.id));
            
            // 编辑按钮
            const editBtn = document.createElement('button');
            editBtn.className = 'p-1.5 text-text-secondary hover:bg-gray-100 rounded-small transition-colors-300';
            editBtn.title = '编辑规则';
            editBtn.innerHTML = '<i class="fa fa-edit"></i>';
            editBtn.addEventListener('click', () => this.editRule(rule.id));
            
            // 删除按钮
            const deleteBtn = document.createElement('button');
            deleteBtn.className = 'p-1.5 text-error hover:bg-red-50 rounded-small transition-colors-300';
            deleteBtn.title = '删除规则';
            deleteBtn.innerHTML = '<i class="fa fa-trash"></i>';
            deleteBtn.addEventListener('click', () => this.deleteRule(rule.id));
            
            ruleActions.appendChild(applyBtn);
            ruleActions.appendChild(editBtn);
            ruleActions.appendChild(deleteBtn);
            
            ruleItem.appendChild(ruleInfo);
            ruleItem.appendChild(ruleActions);
            
            this.dom.rulesContainer.appendChild(ruleItem);
        });
    },
    
    // 获取时间单位显示文本
    getUnitDisplay: function(unit) {
        const unitMap = {
            'second': '秒',
            'minute': '分钟',
            'hour': '小时'
        };
        return unitMap[unit] || unit;
    },
    
    // 从localStorage保存规则
    saveRulesToLocalStorage: function() {
        try {
            localStorage.setItem('logAggregationRules', JSON.stringify(this.rules));
        } catch (e) {
            console.error('保存规则失败:', e);
            this.showNotification('保存规则失败，请稍后重试', 'error');
        }
    },
    
    // 从localStorage加载规则
    loadRules: function() {
        try {
            const savedRules = localStorage.getItem('logAggregationRules');
            if (savedRules) {
                this.rules = JSON.parse(savedRules);
                // 确保rules是数组
                if (!Array.isArray(this.rules)) {
                    this.rules = [];
                }
            } else {
                // 创建默认规则
                this.createDefaultRules();
            }
        } catch (e) {
            console.error('加载规则失败:', e);
            this.rules = [];
            this.showNotification('加载规则失败，使用默认配置', 'warning');
        }
    },
    
    // 创建默认规则
    createDefaultRules: function() {
        this.rules = [
            {
                id: 'default_1',
                name: '登录失败关联访问异常',
                source1: {
                    type: 'auth',
                    filter: 'source_ip',
                    displayType: '认证日志',
                    displayFilter: '源地址'
                },
                source2: {
                    type: 'access',
                    filter: 'source_ip',
                    displayType: '访问日志',
                    displayFilter: '源地址'
                },
                aggregation: {
                    window: 5,
                    unit: 'minute',
                    threshold: {
                        type: 'gte',
                        count: 10
                    }
                },
                description: '规则「登录失败关联访问异常」：将认证日志和访问日志通过源地址和源地址进行关联，在5分钟的聚合窗口内，当关联后的事件≥10次时触发告警。',
                createdAt: new Date().toISOString(),
                updatedAt: new Date().toISOString()
            },
            {
                id: 'default_2',
                name: '攻击行为关联认证失败',
                source1: {
                    type: 'attack',
                    filter: 'source_ip',
                    displayType: '攻击日志',
                    displayFilter: '源地址'
                },
                source2: {
                    type: 'auth',
                    filter: 'source_ip',
                    displayType: '认证日志',
                    displayFilter: '源地址'
                },
                aggregation: {
                    window: 10,
                    unit: 'minute',
                    threshold: {
                        type: 'gte',
                        count: 5
                    }
                },
                description: '规则「攻击行为关联认证失败」：将攻击日志和认证日志通过源地址和源地址进行关联，在10分钟的聚合窗口内，当关联后的事件≥5次时触发告警。',
                createdAt: new Date().toISOString(),
                updatedAt: new Date().toISOString()
            }
        ];
        
        // 保存默认规则
        this.saveRulesToLocalStorage();
    },
    
    // 应用已保存的规则
    applySavedRule: function(ruleId) {
        const rule = this.rules.find(r => r.id === ruleId);
        if (!rule) {
            this.showNotification('规则不存在', 'error');
            return;
        }
        
        // 生成模拟数据
        this.generateSimulatedLogs();
        
        // 应用规则
        this.events = this.applyRule(rule, this.logData);
        
        // 显示结果
        this.displaySimulationResults(rule, this.events);
        this.showNotification(`规则「${rule.name}」应用成功，触发了 ${this.events.length} 个事件`, 'success');
    },
    
    // 编辑规则
    editRule: function(ruleId) {
        const rule = this.rules.find(r => r.id === ruleId);
        if (!rule) {
            this.showNotification('规则不存在', 'error');
            return;
        }
        
        // 填充表单
        this.currentEditRuleId = rule.id;
        this.dom.ruleName.value = rule.name;
        this.dom.source1Type.value = rule.source1.type;
        this.dom.source2Type.value = rule.source2.type;
        
        // 更新过滤选项
        this.updateFilterOptions(this.dom.source1Type, this.dom.source1Filter, 'source1');
        this.updateFilterOptions(this.dom.source2Type, this.dom.source2Filter, 'source2');
        
        // 设置过滤字段值
        this.dom.source1Filter.value = rule.source1.filter;
        this.dom.source2Filter.value = rule.source2.filter;
        
        // 设置聚合配置
        this.dom.aggregationWindow.value = rule.aggregation.window;
        this.dom.windowUnit.value = rule.aggregation.unit;
        this.dom.thresholdType.value = rule.aggregation.threshold.type;
        this.dom.thresholdCount.value = rule.aggregation.threshold.count;
        
        // 更新预览和描述
        this.updateCorrelationPreview();
        this.updateRuleDescription();
        
        // 滚动到表单顶部
        document.getElementById('rule-config').scrollIntoView({ behavior: 'smooth' });
    },
    
    // 删除规则
    deleteRule: function(ruleId) {
        if (confirm('确定要删除这条规则吗？删除后将无法恢复。')) {
            this.rules = this.rules.filter(r => r.id !== ruleId);
            this.saveRulesToLocalStorage();
            this.renderRulesList();
            this.showNotification('规则已成功删除', 'success');
        }
    },
    
    // 生成模拟日志
    generateSimulatedLogs: function() {
        this.logData = [];
        const now = Date.now();
        
        // 生成攻击日志
        for (let i = 0; i < 300; i++) {
            const time = now - Math.random() * 3600000; // 过去1小时内的随机时间
            let sourceIp = `192.168.1.${Math.floor(Math.random() * 254) + 1}`;
            const destIp = `10.0.0.${Math.floor(Math.random() * 254) + 1}`;
            
            // 确保有一些IP会触发阈值
            if (i < 60) {
                sourceIp = '192.168.1.100'; // 这个IP会有更多事件
            }
            
            this.logData.push({
                id: `attack_${i}`,
                type: 'attack',
                timestamp: time,
                source_ip: sourceIp,
                dest_ip: destIp,
                attack_type: ['SQL注入', 'XSS攻击', '暴力破解', '端口扫描'][Math.floor(Math.random() * 4)],
                severity: ['低', '中', '高'][Math.floor(Math.random() * 3)]
            });
        }
        
        // 生成认证日志
        for (let i = 0; i < 500; i++) {
            const time = now - Math.random() * 3600000;
            let sourceIp = `192.168.1.${Math.floor(Math.random() * 254) + 1}`;
            const username = `user${Math.floor(Math.random() * 100)}`;
            
            // 确保有一些IP会触发阈值
            if (i < 80) {
                sourceIp = '192.168.1.100'; // 这个IP会有更多事件
            }
            
            this.logData.push({
                id: `auth_${i}`,
                type: 'auth',
                timestamp: time,
                source_ip: sourceIp,
                username: username,
                auth_type: ['登录', '注销', '权限变更'][Math.floor(Math.random() * 3)],
                status: ['成功', '失败'][Math.floor(Math.random() * 2)]
            });
        }
        
        // 生成访问日志
        for (let i = 0; i < 1000; i++) {
            const time = now - Math.random() * 3600000;
            let sourceIp = `192.168.1.${Math.floor(Math.random() * 254) + 1}`;
            
            // 确保有一些IP会触发阈值
            if (i < 150) {
                sourceIp = '192.168.1.100'; // 这个IP会有更多事件
            }
            
            this.logData.push({
                id: `access_${i}`,
                type: 'access',
                timestamp: time,
                source_ip: sourceIp,
                url: `/api/${['users', 'data', 'reports', 'settings'][Math.floor(Math.random() * 4)]}`
            });
        }
        
        // 在展示框中显示日志信息
        this.displayLogInfo();
        
        // 生成一些测试事件，确保有事件可以展示
        this.generateTestEvents();
        
        this.showNotification('模拟日志生成成功', 'success');
    },
    
    // 生成测试事件，用于在查看触发事件时展示
    generateTestEvents: function() {
        // 确保事件数组为空
        this.events = [];
        
        // 基于生成的日志创建一些测试事件
        const specialIp = '192.168.1.100';
        
        // 查找该IP的攻击日志
        const attackLogs = this.logData.filter(log => log.type === 'attack' && log.source_ip === specialIp);
        // 查找该IP的认证日志
        const authLogs = this.logData.filter(log => log.type === 'auth' && log.source_ip === specialIp);
        // 查找该IP的访问日志
        const accessLogs = this.logData.filter(log => log.type === 'access' && log.source_ip === specialIp);
        
        // 创建关联规则
        const sampleRule = {
            name: '测试关联规则',
            source1: {
                type: 'attack',
                filter: 'source_ip'
            },
            source2: {
                type: 'auth',
                filter: 'source_ip'
            },
            aggregation: {
                window: 5,
                unit: 'minute',
                threshold: {
                    type: 'gte',
                    count: 10
                }
            }
        };
        
        // 创建多个触发事件
        // 1. IP相关的攻击+认证事件
        if (attackLogs.length > 0 && authLogs.length > 0) {
            this.events.push({
                id: Date.now() + '_ip_attack_auth',
                correlationKey: specialIp,
                count: attackLogs.length + authLogs.length,
                timestamp: new Date().toISOString(),
                rule: sampleRule,
                events: [
                    { log1: attackLogs[0], log2: authLogs[0], timestamp: Math.max(attackLogs[0].timestamp, authLogs[0].timestamp) },
                    { log1: attackLogs[1], log2: authLogs[1], timestamp: Math.max(attackLogs[1].timestamp, authLogs[1].timestamp) }
                ]
            });
        }
        
        // 2. IP相关的访问+认证事件
        if (accessLogs.length > 0 && authLogs.length > 0) {
            const accessAuthRule = { ...sampleRule };
            accessAuthRule.source1.type = 'access';
            accessAuthRule.name = '访问+认证关联规则';
            
            this.events.push({
                id: Date.now() + '_ip_access_auth',
                correlationKey: specialIp,
                count: accessLogs.length + authLogs.length,
                timestamp: new Date().toISOString(),
                rule: accessAuthRule,
                events: [
                    { log1: accessLogs[0], log2: authLogs[0], timestamp: Math.max(accessLogs[0].timestamp, authLogs[0].timestamp) },
                    { log1: accessLogs[1], log2: authLogs[1], timestamp: Math.max(accessLogs[1].timestamp, authLogs[1].timestamp) }
                ]
            });
        }
        
        // 3. 创建一个针对高频率登录失败的事件
        const failedAuthLogs = this.logData.filter(log => log.type === 'auth' && log.status === '失败');
        if (failedAuthLogs.length > 0) {
            const failedLoginRule = { ...sampleRule };
            failedLoginRule.source1.type = 'auth';
            failedLoginRule.source1.filter = 'username';
            failedLoginRule.source2.type = 'auth';
            failedLoginRule.source2.filter = 'username';
            failedLoginRule.name = '登录失败关联规则';
            
            // 查找失败登录最多的用户名
            const usernameCounts = {};
            failedAuthLogs.forEach(log => {
                usernameCounts[log.username] = (usernameCounts[log.username] || 0) + 1;
            });
            
            const maxUsername = Object.keys(usernameCounts).reduce((a, b) => 
                usernameCounts[a] > usernameCounts[b] ? a : b
            );
            
            const userFailedLogs = failedAuthLogs.filter(log => log.username === maxUsername);
            
            this.events.push({
                id: Date.now() + '_failed_login',
                correlationKey: maxUsername,
                count: userFailedLogs.length,
                timestamp: new Date().toISOString(),
                rule: failedLoginRule,
                events: userFailedLogs.slice(0, 2).map(log => ({ log1: log, log2: log, timestamp: log.timestamp }))
            });
        }
        
        // 按事件数量降序排序
        this.events.sort((a, b) => b.count - a.count);
    },
    
    // 显示日志信息
    displayLogInfo: function() {
        const attackLogs = this.logData.filter(log => log.type === 'attack').length;
        const authLogs = this.logData.filter(log => log.type === 'auth').length;
        const accessLogs = this.logData.filter(log => log.type === 'access').length;
        const totalLogs = this.logData.length;
        
        const logInfoHtml = `
            <div class="log-summary">
                <h4 class="font-medium mb-2">模拟日志生成统计</h4>
                <div class="grid grid-cols-2 gap-2 text-sm">
                    <div class="p-2 bg-gray-50 rounded">
                        <div class="text-text-secondary">攻击日志</div>
                        <div class="font-medium">${attackLogs} 条</div>
                    </div>
                    <div class="p-2 bg-gray-50 rounded">
                        <div class="text-text-secondary">认证日志</div>
                        <div class="font-medium">${authLogs} 条</div>
                    </div>
                    <div class="p-2 bg-gray-50 rounded">
                        <div class="text-text-secondary">访问日志</div>
                        <div class="font-medium">${accessLogs} 条</div>
                    </div>
                    <div class="p-2 bg-gray-50 rounded">
                        <div class="text-text-secondary">日志总数</div>
                        <div class="font-medium">${totalLogs} 条</div>
                    </div>
                </div>
                <div class="mt-3 text-xs text-text-secondary">
                    <p>• 生成时间范围：过去1小时内的随机时间</p>
                    <p>• 包含特殊IP（192.168.1.100）的日志数量较多，更容易触发规则</p>
                </div>
            </div>
        `;
        
        // 显示在结果展示框
        if (this.dom.resultsContent) {
            this.dom.resultsContent.innerHTML = logInfoHtml;
        } else if (this.dom.simulationResults) {
            // 如果没有resultsContent，使用simulationResults作为备选
            this.dom.simulationResults.classList.remove('hidden');
            this.dom.simulationResults.innerHTML = logInfoHtml;
        }
    },
    
    // 清空结果展示框
    clearResults: function() {
        if (this.dom.resultsContent) {
            this.dom.resultsContent.innerHTML = `
                <div class="text-center py-8">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-12 w-12 text-gray-300 mx-auto mb-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                    </svg>
                    <p class="text-text-secondary">点击生成模拟日志或查看触发事件</p>
                </div>
            `;
        } else if (this.dom.simulationResults) {
            this.dom.simulationResults.innerHTML = `
                <div class="text-center py-8">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-12 w-12 text-gray-300 mx-auto mb-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                    </svg>
                    <p class="text-text-secondary">点击生成模拟日志或查看触发事件</p>
                </div>
            `;
        }
        
        // 显示通知
        this.showNotification('结果已清空', 'info');
    },
    
    // 应用规则到日志数据
    applyRule: function(rule, logs) {
        const events = [];
        const correlationMap = new Map();
        
        // 转换时间窗口为毫秒
        const windowMs = this.convertWindowToMs(rule.aggregation.window, rule.aggregation.unit);
        const now = Date.now();
        const windowStart = now - windowMs;
        
        // 过滤时间范围内的日志
        const timeFilteredLogs = logs.filter(log => log.timestamp >= windowStart && log.timestamp <= now);
        
        // 分离两个源的日志
        const source1Logs = timeFilteredLogs.filter(log => log.type === rule.source1.type);
        const source2Logs = timeFilteredLogs.filter(log => log.type === rule.source2.type);
        
        // 关联日志
        source1Logs.forEach(log1 => {
            const key1 = log1[rule.source1.filter];
            if (key1) {
                source2Logs.forEach(log2 => {
                    const key2 = log2[rule.source2.filter];
                    if (key2 && key1 === key2) {
                        // 找到关联
                        const correlationKey = `${key1}`;
                        if (!correlationMap.has(correlationKey)) {
                            correlationMap.set(correlationKey, []);
                        }
                        correlationMap.get(correlationKey).push({
                            log1: log1,
                            log2: log2,
                            timestamp: Math.max(log1.timestamp, log2.timestamp)
                        });
                    }
                });
            }
        });
        
        // 检查阈值
        const thresholdType = rule.aggregation.threshold.type;
        const thresholdCount = rule.aggregation.threshold.count;
        
        correlationMap.forEach((correlatedEvents, key) => {
            let shouldTrigger = false;
            const eventCount = correlatedEvents.length;
            
            switch (thresholdType) {
                case 'gte':
                    shouldTrigger = eventCount >= thresholdCount;
                    break;
                case 'gt':
                    shouldTrigger = eventCount > thresholdCount;
                    break;
                case 'lte':
                    shouldTrigger = eventCount <= thresholdCount;
                    break;
                case 'lt':
                    shouldTrigger = eventCount < thresholdCount;
                    break;
                case 'eq':
                    shouldTrigger = eventCount === thresholdCount;
                    break;
            }
            
            if (shouldTrigger) {
                events.push({
                    id: Date.now() + '_' + events.length,
                    correlationKey: key,
                    count: eventCount,
                    timestamp: new Date().toISOString(),
                    rule: rule,
                    events: correlatedEvents.slice(0, 10) // 只保存前10个事件用于展示
                });
            }
        });
        
        return events.sort((a, b) => b.count - a.count); // 按事件数量降序排序
    },
    
    // 转换时间窗口为毫秒
    convertWindowToMs: function(windowValue, windowUnit) {
        switch (windowUnit) {
            case 'second':
                return windowValue * 1000;
            case 'minute':
                return windowValue * 60 * 1000;
            case 'hour':
                return windowValue * 60 * 60 * 1000;
            default:
                return windowValue * 60 * 1000; // 默认分钟
        }
    },
    
    // 显示模拟结果
    displaySimulationResults: function(rule, events) {
        this.dom.simulationResults.innerHTML = '';
        this.dom.simulationResults.classList.remove('hidden');
        
        if (events.length === 0) {
            const emptyState = document.createElement('div');
            emptyState.className = 'text-center text-text-secondary py-4';
            emptyState.innerHTML = `
                <i class="fa fa-info-circle text-lg mb-1"></i>
                <p>没有触发任何事件</p>
            `;
            this.dom.simulationResults.appendChild(emptyState);
            return;
        }
        
        // 显示事件统计
        const stats = document.createElement('div');
        stats.className = 'mb-4 p-2 bg-gray-50 rounded-small text-sm';
        stats.textContent = `共触发 ${events.length} 个事件，聚合窗口：${rule.aggregation.window}${this.getUnitDisplay(rule.aggregation.unit)}，阈值：${rule.aggregation.threshold.type}${rule.aggregation.threshold.count}`;
        this.dom.simulationResults.appendChild(stats);
        
        // 显示每个事件
        events.forEach(event => {
            const eventItem = document.createElement('div');
            eventItem.className = 'mb-3 p-3 bg-white rounded-small border border-gray-200';
            
            const eventHeader = document.createElement('div');
            eventHeader.className = 'flex justify-between items-center mb-2';
            
            const eventTitle = document.createElement('h4');
            eventTitle.className = 'font-medium text-text-primary';
            eventTitle.textContent = `关联键：${event.correlationKey}`;
            
            const eventCount = document.createElement('span');
            eventCount.className = 'px-2 py-0.5 bg-primary-light text-primary-dark rounded-full text-xs';
            eventCount.textContent = `事件数：${event.count}`;
            
            eventHeader.appendChild(eventTitle);
            eventHeader.appendChild(eventCount);
            
            const eventDetails = document.createElement('div');
            eventDetails.className = 'text-sm text-text-secondary space-y-1';
            
            // 获取显示类型
            const source1Type = rule.source1.displayType || this.getLogTypeDisplayName(rule.source1.type);
            const source2Type = rule.source2.displayType || this.getLogTypeDisplayName(rule.source2.type);
            
            // 获取显示字段名
            const source1Filter = rule.source1.displayFilter || this.getFieldDisplayName(rule.source1.filter);
            const source2Filter = rule.source2.displayFilter || this.getFieldDisplayName(rule.source2.filter);
            
            eventDetails.innerHTML = `
                <div>关联类型：${source1Type} + ${source2Type}</div>
                <div>关联字段：${source1Filter} = ${source2Filter}</div>
                <div>触发时间：${new Date(event.timestamp).toLocaleString()}</div>
            `;
            
            eventItem.appendChild(eventHeader);
            eventItem.appendChild(eventDetails);
            
            this.dom.simulationResults.appendChild(eventItem);
        });
    },
    
    // 查看触发的事件
    viewTriggeredEvents: function() {
        if (this.events.length === 0) {
            this.showNotification('暂无触发事件', 'info');
            
            // 显示无事件提示
            if (this.dom.resultsContent) {
                this.dom.resultsContent.innerHTML = `
                    <div class="text-center py-8">
                        <i class="fa fa-info-circle text-4xl mb-2 text-gray-300"></i>
                        <p class="text-text-secondary">当前没有触发的事件记录</p>
                        <p class="text-xs text-text-tertiary mt-2">请先生成模拟日志或应用规则</p>
                    </div>
                `;
            }
            
            return;
        }

        // 在展示框中显示事件记录
        const eventsHtml = `
            <div class="events-container">
                <h4 class="font-medium mb-3">触发事件记录 (共 ${this.events.length} 个事件)</h4>
                <div class="space-y-3 max-h-[calc(80vh-150px)] overflow-y-auto">
                    ${this.events.map((event, index) => {
                        // 根据事件类型选择不同的颜色标记
                        let badgeBgColor = 'bg-success/10';
                        let badgeTextColor = 'text-success';
                        
                        if (event.correlationKey.includes('192.168.1.100')) {
                            badgeBgColor = 'bg-warning/10';
                            badgeTextColor = 'text-warning';
                        }
                        
                        if (event.rule?.name?.includes('登录失败')) {
                            badgeBgColor = 'bg-danger/10';
                            badgeTextColor = 'text-danger';
                        }
                        
                        // 格式化事件示例数据
                        let exampleDataHtml = '无示例数据';
                        if (event.events && event.events.length > 0) {
                            const example = event.events[0];
                            if (example.log1 && example.log2) {
                                // 提取关键信息展示，而不是完整的JSON
                                const log1Info = example.log1.type === 'attack' ? 
                                    `${example.log1.attack_type} (${example.log1.severity})` : 
                                    (example.log1.type === 'auth' ? 
                                    `${example.log1.auth_type} ${example.log1.status}` :
                                    `${example.log1.method} ${example.log1.url}`);
                                
                                const log2Info = example.log2.type === 'attack' ? 
                                    `${example.log2.attack_type} (${example.log2.severity})` : 
                                    (example.log2.type === 'auth' ? 
                                    `${example.log2.auth_type} ${example.log2.status}` :
                                    `${example.log2.method} ${example.log2.url}`);
                                
                                exampleDataHtml = `
                                    <div class="space-y-1">
                                        <div><span class="font-medium">日志1:</span> ${log1Info}</div>
                                        <div><span class="font-medium">日志2:</span> ${log2Info}</div>
                                    </div>
                                `;
                            } else if (example.log1) {
                                // 单个日志的情况
                                const logInfo = example.log1.type === 'attack' ? 
                                    `${example.log1.attack_type} (${example.log1.severity})` : 
                                    (example.log1.type === 'auth' ? 
                                    `${example.log1.auth_type} ${example.log1.status}` :
                                    `${example.log1.method} ${example.log1.url}`);
                                
                                exampleDataHtml = `<div><span class="font-medium">日志:</span> ${logInfo}</div>`;
                            }
                        }
                        
                        return `
                            <div class="p-3 bg-gray-50 rounded-small border border-gray-200 hover:shadow-md transition-shadow">
                                <div class="flex justify-between items-center mb-2">
                                    <h5 class="font-medium">事件 #${index + 1}</h5>
                                    <span class="px-2 py-0.5 ${badgeBgColor} ${badgeTextColor} rounded-full text-xs">${event.correlationKey}</span>
                                </div>
                                <div class="text-sm text-text-secondary space-y-1">
                                    <div>关联键: <span class="font-medium">${event.correlationKey}</span></div>
                                    <div>事件数量: <span class="font-medium">${event.count} 条</span></div>
                                    <div>触发时间: <span class="font-medium">${new Date(event.timestamp).toLocaleString()}</span></div>
                                    <div>规则: <span class="font-medium">${event.rule?.name || '当前配置'}</span></div>
                                    <!-- 添加关联类型和关联字段信息 -->
                                    <div>关联类型: <span class="font-medium">
                                        ${event.rule?.source1 && event.rule?.source2 ? 
                                            `${LogAggregator.getLogTypeDisplayName(event.rule.source1.type)} + ${LogAggregator.getLogTypeDisplayName(event.rule.source2.type)}` : 
                                            '未知'
                                        }
                                    </span></div>
                                    <div>关联字段: <span class="font-medium">
                                        ${event.rule?.source1 && event.rule?.source2 ? 
                                            `${LogAggregator.getFieldDisplayName(event.rule.source1.filter)} = ${LogAggregator.getFieldDisplayName(event.rule.source2.filter)}` : 
                                            '未知'
                                        }
                                    </span></div>
                                    <div class="mt-2">
                                        <div class="font-medium text-xs mb-1">关联日志示例:</div>
                                        <div class="bg-white p-2 rounded-small border border-gray-200 text-xs mt-1 overflow-auto">
                                            ${exampleDataHtml}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        `;
                    }).join('')}
                </div>
            </div>
        `;

        // 显示在结果展示框
        if (this.dom.resultsContent) {
            this.dom.resultsContent.innerHTML = eventsHtml;
        } else if (this.dom.simulationResults) {
            this.dom.simulationResults.classList.remove('hidden');
            this.dom.simulationResults.innerHTML = eventsHtml;
        }

        // 显示成功通知
        this.showNotification(`已显示 ${this.events.length} 个触发事件`, 'success');
    },
    
    // 导出规则
    exportRules: function() {
        if (this.rules.length === 0) {
            this.showNotification('没有可导出的规则', 'warning');
            return;
        }
        
        const dataStr = JSON.stringify(this.rules, null, 2);
        const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr);
        
        const exportFileDefaultName = `log-aggregation-rules-${new Date().toISOString().split('T')[0]}.json`;
        
        const linkElement = document.createElement('a');
        linkElement.setAttribute('href', dataUri);
        linkElement.setAttribute('download', exportFileDefaultName);
        linkElement.click();
        
        this.showNotification('规则导出成功', 'success');
    },
    
    // 导入规则
    importRules: function(file) {
        const reader = new FileReader();
        
        reader.onload = (e) => {
            try {
                const importedRules = JSON.parse(e.target.result);
                
                if (!Array.isArray(importedRules)) {
                    throw new Error('无效的规则格式');
                }
                
                // 合并规则
                const existingIds = new Set(this.rules.map(r => r.id));
                const newRules = importedRules.filter(r => !existingIds.has(r.id));
                
                this.rules = [...newRules, ...this.rules];
                this.saveRulesToLocalStorage();
                this.renderRulesList();
                
                this.showNotification(`已成功导入 ${newRules.length} 条新规则`, 'success');
            } catch (e) {
                console.error('导入规则失败:', e);
                this.showNotification('导入规则时遇到问题，请检查文件是否为有效的JSON格式', 'error');
            }
        };
        
        reader.onerror = () => {
            this.showNotification('无法读取文件，请确保文件可访问且格式正确', 'error');
        };
        
        reader.readAsText(file);
    },
    
    // 显示通知 - 类似layer.alert的效果
    showNotification: function(message, type = 'info') {
        // 移除之前可能存在的通知，避免堆积
        const oldNotifications = document.querySelectorAll('.message-notification');
        oldNotifications.forEach(notification => notification.remove());
        
        // 创建通知容器
        const notification = document.createElement('div');
        notification.className = 'message-notification';
        
        // 设置基础样式
        notification.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            padding: 16px 24px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            z-index: 9999;
            font-size: 14px;
            color: #333;
            max-width: 90%;
            text-align: center;
            opacity: 0;
            transition: opacity 0.3s ease;
        `;
        
        // 根据类型设置不同样式
        if (type === 'warning') {
            notification.style.backgroundColor = '#fff7e6';
            notification.style.border = '1px solid #ffd591';
            notification.style.color = '#d46b08';
        } else if (type === 'error') {
            notification.style.backgroundColor = '#fff2f0';
            notification.style.border = '1px solid #ffccc7';
            notification.style.color = '#cf1322';
        } else if (type === 'success') {
            notification.style.backgroundColor = '#f6ffed';
            notification.style.border = '1px solid #b7eb8f';
            notification.style.color = '#389e0d';
        } else {
            notification.style.backgroundColor = '#f0f5ff';
            notification.style.border = '1px solid #adc6ff';
            notification.style.color = '#1890ff';
        }
        
        // 设置消息内容
        notification.textContent = message;
        
        // 添加到文档
        document.body.appendChild(notification);
        
        // 触发动画显示
        setTimeout(() => {
            notification.style.opacity = '1';
        }, 10);
        
        // 自动关闭
        setTimeout(() => {
            notification.style.opacity = '0';
            setTimeout(() => {
                if (document.body.contains(notification)) {
                    document.body.removeChild(notification);
                }
            }, 300);
        }, 3000);
        
        // 点击关闭
        notification.addEventListener('click', () => {
            notification.style.opacity = '0';
            setTimeout(() => {
                if (document.body.contains(notification)) {
                    document.body.removeChild(notification);
                }
            }, 300);
        });
    }
};

// 页面加载完成后初始化
window.addEventListener('DOMContentLoaded', () => {
    LogAggregator.init();
});